package cn.serenedream.housedecoration.serivce;

import cn.hutool.core.util.IdUtil;
import cn.serenedream.housedecoration.dao.ModelRepository;
import cn.serenedream.housedecoration.dao.ProductsRepository;
import cn.serenedream.housedecoration.dto.ProductWithModelDTO;
import cn.serenedream.housedecoration.entity.Model;
import cn.serenedream.housedecoration.entity.Products;
import cn.serenedream.housedecoration.entity.Sale;
import cn.serenedream.housedecoration.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;
import java.util.Optional;

@Service
public class ProductsService {
    @Autowired
    ProductsRepository productsRepository;

    @Autowired
    ModelRepository modelRepository;

    public Long count() {
        return productsRepository.count();
    }

    public Page<Products> list(Integer currentPage, Integer pageSize) {
        Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.by("id").descending());
        return productsRepository.findAll(pageable);
    }

    public void save(ProductWithModelDTO pwm) {
        Model model = new Model();
        model.setId(IdUtil.getSnowflakeNextId());
        model.setSize(pwm.getSize());
        model.setThickness(pwm.getThickness());


        Products products = new Products();

        if (pwm.getId() == null || Objects.equals("", pwm.getId())){
            products.setId(IdUtil.getSnowflakeNextId());
        } else {
            products.setId(Long.valueOf(pwm.getId()));
        }

        products.setModel(model);
        products.setName(pwm.getProductName());
        BigDecimal bigDecimal = new BigDecimal(pwm.getPrice());
        products.setPrice(bigDecimal.doubleValue());
        products.setAddress(pwm.getProductName());

        modelRepository.save(model);
        productsRepository.save(products);
    }

    public void delete(String id) {
        productsRepository.deleteById(Long.parseLong(id));
    }

    public Page<Products> findByName(Integer currentPage, Integer pageSize, String name) {
        Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.by("id").descending());
        return productsRepository.findByName(name, pageable);
    }

    public Products findById(String s) {
        return productsRepository.findById(new BigDecimal(s).longValue()).get();
    }
}
